package com.mf.framework.component.mybatis.dialect;

import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.ParameterMapping;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.session.Configuration;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * MySql方言实现类
 * User: zhaoming
 * Date: 2017/6/15 10:06
 * To change this template use File | Settings | File Templates.
 */
public class MySqlDialect extends Dialect {

	/**
	 * 设置分页
	 */
	public void setSqlLimit(MetaObject metaObject, BoundSql boundSql, int offset, int limit) {
		Configuration configuration = (Configuration) metaObject.getValue("delegate.configuration");
		//获取SQL
		String sql = trim(boundSql.getSql());
		//获取参数映射
		List<ParameterMapping> parameterMappings = new ArrayList<>();
		if(boundSql.getParameterMappings() != null && boundSql.getParameterMappings().size() > 0){
			parameterMappings = boundSql.getParameterMappings();
		}
		//获取参数对象
		Map<String, Object> parameterObject = (Map<String, Object>)boundSql.getParameterObject();

		StringBuilder sqlBuilder = new StringBuilder();
		sqlBuilder.append(sql);
		if (offset > 0) {
			//设置SQL语句
			sqlBuilder.append(" LIMIT ").append("?").append(", ").append("?").append(SQL_END_DELIMITER);
			//设置参数映射
			parameterMappings.add(new ParameterMapping.Builder(configuration, "_offset", Integer.class).build());
			parameterMappings.add(new ParameterMapping.Builder(configuration, "_limit", Integer.class).build());
			//设置参数值
			parameterObject.put("_offset", offset);
			parameterObject.put("_limit", limit);
		} else {
			//设置SQL语句
			sqlBuilder.append(" LIMIT ").append("?").append(SQL_END_DELIMITER);
			//设置参数映射
			parameterMappings.add(new ParameterMapping.Builder(configuration, "_limit", Integer.class).build());
			//设置参数值
			parameterObject.put("_limit", limit);
		}

		metaObject.setValue("delegate.boundSql.sql", sqlBuilder.toString());
		metaObject.setValue("delegate.boundSql.parameterMappings", parameterMappings);
		metaObject.setValue("delegate.boundSql.parameterObject", parameterObject);
	}
}
